package org.baojie.raft.group;

import org.baojie.raft.node.NodeName;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class RaftGroup {

    public final Map<String, NodeName> group = new ConcurrentHashMap<>(128);

    private final NodeName name;

    public RaftGroup(NodeName name) {
        this.name = name;
    }

    public boolean addMember(String name, NodeName node) {
        Object tmp = group.putIfAbsent(name, node);
        if (null == tmp) {
            return true;
        } else {
            return false;
        }
    }

    public List<NodeName> exceptSelf() {
        List<NodeName> names = new ArrayList<>(group.size());
        Iterator<NodeName> iterator = group.values().iterator();
        while (iterator.hasNext()) {
            NodeName tmp = iterator.next();
            if (tmp != name) {
                names.add(tmp);
            }
        }
        return names;
    }

    public int half() {
        return group.size() / 2;
    }

    public NodeName localName() {
        return name;
    }

}
